<template>
	<view>
		<view class="login-from">
			<view class="logo-container">
				<image class="logo-image" src="/static/header.gif"></image>
				<text class="logo-text">闲言博客</text>
			</view>
			<view class="login-container">
				<view class="login-input-container">
					<text class="login-text">账号：</text>
					<input class="login-input" type="text" v-model="userInfo.username" placeholder="请输入账号" />
				</view>
				<view class="login-input-container">
					<text class="login-text">密码：</text>
					<input class="login-input" type="password" v-model="userInfo.password" placeholder="请输入密码" />
				</view>
				<button type="primary" class="login-button" @click="userLogin">登录</button>
			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="third-login-container">
				<view class="third-login-text">第三方软件登录</view>
				<view class="third-login-icon-container">
					<image class="third-login-item" @click="loginWeixin" src="/static/icons/weixin.png"></image></view>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
import userApi from '@/api/myUser.js';
import md5 from 'js-md5';
export default {
	data() {
		return {
			userInfo: {
				username: '',
				password: ''
			},
		};
	},
	methods: {
		// 普通账密登录
		userLogin() {
			this.userInfo.password = md5(this.userInfo.password);
			userApi.login(this.userInfo).then(res => {
				// token存储到本地缓存，user也是
				uni.setStorage({
					key: 'user',
					data: res.data.user
				});
				uni.setStorage({
					key: 'Authorization',
					data: res.data.token
				})
				// 跳转到我的
				uni.reLaunch({
					url: '/pages/mine/mine'
				})
			});
		},
		// 微信登录APP
		loginWeixin() {
			uni.login({
				provider: 'weixin',
				success(res) {
					// 获取openid
					const openid = res.authResult.openid;
					uni.getUserInfo({
						provider: 'weixin',
						success(infoRes) {
							const userInfo = infoRes.userInfo;
							const loginUser = {
								header: userInfo.avatarUrl,
								sex: userInfo.gender,
								nickname: userInfo.nickName,
								openId: userInfo.openId 
							};
							userApi.loginWXApp(loginUser).then(res=>{
								// token存储到本地缓存，user也是
								uni.setStorage({
									key: 'user',
									data: res.data.user
								});
								uni.setStorage({
									key: 'Authorization',
									data: res.data.token
								})
								// 判断用户名是否存在，让用户直接跳转到首页，否则跳转到完善信息
								const validateLogin = res.data.validateLogin;
								if(validateLogin==="1"){
									// 登录
									// 跳转到我的
									uni.reLaunch({
										url: '/pages/mine/mine'
									});
								}else{
									// 注册
									// 跳转到完善账号密码页面
									uni.navigateTo({
										url: '/pages/set-username/set-username'
									});
								}
							});
						}
					})
				}
			})
		}
	}
};
</script>

<style>
@import url('./index.css');
</style>
